package LeetCode.leetcode394;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;


class Solution {
    public static void main(String[] args) {
        new Solution().decodeString("3[a]2[bc]");
    }
    public String decodeString(String s) {
        Deque<Character> stack = new ArrayDeque<>();
        for(char c : s.toCharArray()){
            if (c == ']'){
                StringBuilder sb = new StringBuilder();
                int loop = 0;
                while(!stack.isEmpty() && stack.peek() != '['){
                    sb.append(stack.pop());
                }
                if (stack.peek() == '['){
                    stack.pop();
                }
                StringBuilder loopSb = new StringBuilder();
                while (!stack.isEmpty() && stack.peek() - '0' >= 0 && '9' - stack.peek() >= 0){
                    loopSb.append(stack.pop());
                }
                loop = Integer.parseInt(loopSb.reverse().toString());
                for (int i = 0; i < loop; i++) {
                    for (int j = sb.length() - 1; j >= 0 ; j--) {
                        stack.push(sb.charAt(j));
                    }
                }
            }else {
                stack.push(c);
            }
        }
        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()){
            sb.append(stack.pop());
        }
        sb.reverse();
        return sb.toString();
    }
}